<template>
  <div id="app">
    <!-- 搜索栏 -->
    <div class="header">
      <el-input
        v-model="titleInput"
        placeholder="请输入试卷标题"
        clearable
        style="width: 200px; margin-right: 10px;"
      />
      <el-input-number
        v-model="pointsInput"
        placeholder="请输入总分"
        :controls="false"
        style="width: 150px; margin-right: 10px;"
      />
      <el-select
        v-model="openInput"
        placeholder="请选择是否公开"
        clearable
        style="width: 150px; margin-right: 10px;"
      >
        <el-option label="公开" :value="1" />
        <el-option label="不公开" :value="0" />
      </el-select>

      <el-button type="primary" icon="el-icon-search" @click="handleSearch">
        搜索
      </el-button>
      <el-button style="margin-left: 10px;" @click="handleReset">
        重置
      </el-button>
    </div>

    <div class="content">
      <!-- 按钮组 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleCreate">创建试卷</el-button>
        <!-- <el-button
          type="danger"
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button> -->
      </div>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        border
        header-align="center"
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="80" align="center" />
        <el-table-column prop="title" label="试卷标题" align="center" width="400" />
        <el-table-column prop="points" label="总分" align="center" width="180" />
        <el-table-column prop="time" label="考试时间(分钟)" align="center" width="150" />
        <el-table-column label="是否公开" align="center" width="180">
          <template v-slot="{ row }">
            <el-tag :type="row.open === 1 ? 'success' : 'info'">
              {{ row.open === 1 ? '公开' : '不公开' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pass_percentage" label="及格线(%)" align="center" width="200" />
        <el-table-column prop="created_at" label="创建时间" align="center" width="300" />
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button type="text" size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-button
              type="text"
              size="mini"
              style="color: #F56C6C;"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>

            <el-dropdown @command="handleCommand($event, row)">
              <el-button type="text" style="margin-left: 10px;">
                <i class="el-icon-more" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="toDetail">查看详情</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 16px; text-align: center;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      title="试卷详情"
      :visible.sync="detailDialogVisible"
      width="600px"
    >
      <div v-if="currentDetail">
        <el-descriptions border column="2" size="medium">
          <el-descriptions-item label="试卷标题" :span="2">
            {{ currentDetail.title }}
          </el-descriptions-item>
          <el-descriptions-item label="总分">
            {{ currentDetail.points }}
          </el-descriptions-item>
          <el-descriptions-item label="考试时间(分钟)">
            {{ currentDetail.time }}
          </el-descriptions-item>
          <el-descriptions-item label="是否公开">
            {{ currentDetail.open === 1 ? '公开' : '不公开' }}
          </el-descriptions-item>
          <el-descriptions-item label="及格线">
            {{ currentDetail.pass_percentage }}%
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ currentDetail.created_at }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ currentDetail.updated_at }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <!-- <el-button @click="detailDialogVisible = false">关闭</el-button> -->
      </template>
    </el-dialog>

    <!-- 编辑/创建试卷弹窗 -->
    <el-dialog
      :title="isEdit ? '编辑试卷' : '创建试卷'"
      :visible.sync="createDialogVisible"
      width="500px"
      @close="resetCreateForm"
    >
      <el-form
        ref="createForm"
        :model="createForm"
        :rules="createRules"
        label-width="120px"
      >
        <el-form-item label="试卷标题" prop="title">
          <el-input
            v-model="createForm.title"
            placeholder="请输入试卷标题"
            clearable
            maxlength="100"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="是否公开" prop="open">
          <el-select v-model="createForm.open" placeholder="请选择是否公开" clearable style="width: 100%;">
            <el-option label="公开" :value="1" />
            <el-option label="不公开" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="及格线(%)" prop="pass_percentage">
          <el-input-number
            v-model="createForm.pass_percentage"
            :min="0"
            :max="100"
            :step="1"
            placeholder="请输入及格线百分比"
            style="width: 100%;"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreate">{{ isEdit ? '保存' : '创建' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getTestPaper, setUpPaper, deletePaper, modifyPaper } from '@/api/question'

export default {
  name: 'PaperList',
  data() {
    // 验证规则
    const validatePassPercentage = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        callback(new Error('请输入及格线'))
      } else if (value < 0 || value > 100) {
        callback(new Error('及格线必须在 0-100 之间'))
      } else {
        callback()
      }
    }
    return {
      tableData: [],
      page: 1,
      pageSize: 10,
      total: 0,

      titleInput: '',
      pointsInput: null,
      openInput: null,

      selectedRows: [],
      detailDialogVisible: false,
      currentDetail: null,

      createDialogVisible: false,
      isEdit: false, // 编辑模式标志
      createForm: {
        id: null, // 编辑时 ID
        title: '',
        open: null,
        pass_percentage: null
      },
      createRules: {
        title: [
          { required: true, message: '请输入试卷标题', trigger: 'blur' },
          { min: 1, max: 100, message: '标题长度为 1-100 字符', trigger: 'blur' }
        ],
        open: [
          { required: true, message: '请选择是否公开', trigger: 'change' }
        ],
        pass_percentage: [
          { required: true, validator: validatePassPercentage, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.fetchData()
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      const params = {
        page: this.page,
        paginate: this.pageSize,
        title: this.titleInput,
        points: this.pointsInput,
        open: this.openInput,
        course_id: 10
      }

      try {
        const res = await getTestPaper(params)
        console.log('原始API响应:', res)

        if (res && res.data) {
          this.tableData = res.data

          this.total = res.meta?.total || 0
        }
      } catch (error) {
        console.error('获取试卷数据失败:', error)
        this.$message.error('获取试卷数据失败')
      }
    },
    handleSearch() {
      this.page = 1
      this.fetchData()
    },
    handleReset() {
      this.titleInput = ''
      this.pointsInput = null
      this.openInput = null
      this.page = 1
      this.fetchData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.page = val
      this.fetchData()
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    // handleCreate 打开弹窗
    handleCreate() {
      this.isEdit = false
      this.createForm.title = ''
      this.createForm.open = null
      this.createForm.pass_percentage = null
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs.createForm.clearValidate() // 清空验证
      })
    },
    // handleEdit 打开弹窗
    handleEdit(row) {
      this.isEdit = true
      this.createForm.id = row.id
      this.createForm.title = row.title
      this.createForm.open = row.open
      this.createForm.pass_percentage = row.pass_percentage
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs.createForm.clearValidate() // 清空验证
      })
    },
    // 重置创建表单
    resetCreateForm() {
      this.createForm = {
        id: null,
        title: '',
        open: null,
        pass_percentage: null
      }
      this.$refs.createForm.resetFields()
    },
    // 提交创建/编辑
    submitCreate() {
      this.$refs.createForm.validate(async(valid) => {
        if (valid) {
          try {
            let res
            if (this.isEdit) {
              const params = {
                id: this.createForm.id,
                title: this.createForm.title,
                open: this.createForm.open,
                pass_percentage: this.createForm.pass_percentage
              }
              res = await modifyPaper(params)
              this.$message.success('修改成功')
            } else {
              const params = {
                title: this.createForm.title,
                pass_percentage: this.createForm.pass_percentage,
                time: 60 // 创建时默认 time
              }
              res = await setUpPaper(params)
              this.$message.success('创建成功')
            }
            console.log(`${this.isEdit ? '修改' : '创建'}试卷结果：`, res)
            this.createDialogVisible = false // 关闭弹窗
            this.resetCreateForm() // 重置表单
            this.fetchData() // 刷新列表
          } catch (error) {
            console.error(`${this.isEdit ? '修改' : '创建'}试卷失败:`, error)
            if (error.response) {
              console.error('状态码:', error.response.status)
              console.error('错误响应数据:', error.response.data)
            }
            this.$message.error(`${this.isEdit ? '修改' : '创建'}失败，请检查参数`)
          }
        } else {
          this.$message.warning('请检查表单输入')
        }
      })
    },
    handleDelete(id) {
      this.$confirm('确定删除该试卷吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deletePaper({ id })
          this.$message.success('删除成功')
          this.fetchData() // 刷新列表
        } catch (error) {
          console.error('单个删除失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 用户取消，不做任何操作
        console.log('用户取消删除')
      })
    },
    // 批量删除方法
    async handleBatchDelete() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要删除的试卷')
        return
      }
      this.$confirm(`确定批量删除 ${this.selectedRows.length} 个试卷吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          // 循环删除每个 ID（如果有批量接口，替换为单次调用）
          for (const row of this.selectedRows) {
            await deletePaper({ id: row.id })
          }
          this.$message.success(`批量删除成功，共 ${this.selectedRows.length} 个`)
          this.selectedRows = [] // 清空选中
          this.fetchData() // 刷新列表
        } catch (error) {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }).catch(() => {
        // 用户取消，不做任何操作
        console.log('用户取消批量删除')
      })
    },
    handleCommand(command, row) {
      if (command === 'toDetail') {
        this.currentDetail = row
        this.detailDialogVisible = true
      }
    }
  }
}
</script>

<style scoped lang="scss">
#app {
  padding: 20px;
}
.header {
  background-color: #fff;
  width: 100%;
  margin-bottom: 20px;
  padding: 10px;
  display: flex;
  align-items: center;
}
.content {
  background-color: #fff;
  padding: 20px;
}
.toolbar {
  margin-bottom: 12px;
}

::v-deep .el-form-item__label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
